<template>
  <div class="statisticsInfo-task">
    <div class="statisticsInfo-head">
      <div class="pieChartBox">
        <div class="pieChart">
          <echartsPie
            :echartsName="'taskPie'"
            :taskOption="taskOption"
            :title="'任务完成度'"
            v-loading="taskCountLoading"
          />
          <echartsPie
            :echartsName="'scorePie'"
            :reviewOption="reviewOption"
            :title="'批阅统计'"
            v-loading="tableLoading"
          />
        </div>
        <div class="searchInput">
          <el-input
            placeholder="学号/姓名"
            suffix-icon="el-input__icon el-icon-search"
            v-model="search"
          >
          </el-input>
        </div>
      </div>
      <div class="barChart">
        <carouselEchartsBar
          :taskCount="taskCount"
          :finshCount="finshCount"
          :studyCount="studyCount"
          :width="`750px`"
          :height="`216px`"
          v-loading="taskCountLoading"
        />
      </div>
    </div>
    <div class="tableBox">
      <el-table
        ref="filterTable"
        :data="filterStuData"
        style="width: 100%"
        max-height="554"
        v-loading="tableLoading"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="stuNum" label="学号" align="center" sortable />
        <el-table-column
          prop="realName"
          label="姓名"
          align="center"
          :formatter="formatterName"
        />
        <el-table-column
          prop="className"
          label="班级"
          align="center"
          sortable
          column-key="className"
          :filters="filterClass"
          :filter-method="filterHandler_class"
        />
        <el-table-column
          prop="taskStateCount"
          label="任务状态"
          align="center"
          sortable
          column-key="taskStateCount"
          :filters="[
            { value: '有未完成任务', text: '有未完成任务' },
            { value: '全部完成', text: '全部完成' },
          ]"
          :filter-method="filterHandler_taksState"
        >
          <!-- :formatter="taskStateFormatter" -->
          <template slot-scope="scope">
            <span style="display: inline-block; min-width: 90px">{{
              taskStateFormatter(scope.row, scope.column)
            }}</span>
            <span style="margin-left: 10px"
              ><el-button size="mini" @click="handleOpenDetail(scope.row, true)"
                >详情</el-button
              ></span
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="reviewStateCount"
          label="批阅状态"
          align="center"
          sortable
          column-key="reviewStateCount"
          :filters="[
            { value: '有未批阅任务', text: '有未批阅任务' },
            { value: '已全部批阅', text: '已全部批阅' },
          ]"
          :filter-method="filterHandler_reviewState"
        >
          <!-- :formatter="reviewStateFormatter" -->
          <template slot-scope="scope">
            <span style="display: inline-block; min-width: 90px">{{
              reviewStateFormatter(scope.row, scope.column)
            }}</span>
            <span style="margin-left: 10px"
              ><el-button
                size="mini"
                @click="handleOpenDetail(scope.row, false)"
                >详情</el-button
              ></span
            >
          </template>
        </el-table-column>
      </el-table>
      <chartDialog
        :show="show"
        :isTask="isTask"
        :currStu="currStu"
        :sunChartData="sunChartData"
        @handleClose="handleCloseDialog"
      />
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
const carouselEchartsBar = () =>
  import("@/components/carouselEcharts/carouselEchartsBar");
const echartsPie = () => import("@/components/echarts/echartsPie");
const chartDialog = () => import("./component/chartDialog.vue");
export default {
  components: {
    carouselEchartsBar,
    echartsPie,
    chartDialog,
  },
  data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
          tag: "家",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
          tag: "公司",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
          tag: "家",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
          tag: "公司",
        },
      ],
      show: false,
      sunChartData: [],
      isTask: false,
      currStu: {},
      search: "",
    };
  },
  props: {
    courseInfo: Object,
    taskCount: Array,
    finshCount: Object,
    studyCount: Object,
    taskOption: Object,
    reviewOption: Object,
    studenData: Array,
    studentsList: Array, // 选了这门课的学生
    tableLoading: Boolean,
    taskCountLoading: Boolean,
    taskIDforTaskGruopID: Object,
  },
  computed: {
    ...mapState({
      classList: (state) => state.class.classList
    }),
    filterClass() {
      let classList = [];
      // 把学生绑定的班级添加到数组
      this.studenData.forEach((item) => {
        if (
          item.className &&
          !classList.some((citem) => citem.value == item.className)
        ) {
          classList.push({ text: item.className, value: item.className, classID: item.classID });
        }
      });
      // 把课程原有班级也加上
      if (this.filterCourseClass?.length) {
        this.filterCourseClass.forEach(item => {
          if (item.className && !classList.some((citem) => citem.value == item.className)) {
            classList.push({ text: item.className, value: item.className, classID: item.classID });
          }
        })
      }
      return classList;
    },
    // 获取当前课程班级数据
    filterCourseClass() {
      if (this.courseInfo.classIDList) {
        const classList = this.courseInfo.classIDList.split(',').map(i => Number(i))
        return this.classList.filter(i => classList.some(s => i.classID == s))
      } else return []
    },
    filterStuData() {
      if (this.search) {
        return this.studenData.filter(
          (item) =>
            item.realName?.indexOf(this.search) !== -1 ||
            item.stuNum?.indexOf(this.search) !== -1
        );
      }
      return this.studenData;
    },
  },
  methods: {
    filterHandler(value, row, column) {
      const property = column["property"];
      return row[property] === value;
    },
    // 过滤班级信息
    filterHandler_class(value, row, column) {
      const property = column["property"];
      const cData = column.filters.find(item => item.value == value)
      let uOtherClassList = [] 
      if (row.otherClassIDList) {
        uOtherClassList = row.otherClassIDList.split(',').map(i => Number(i))
      }
      return row[property] === value || uOtherClassList.indexOf(cData.classID) !== -1;
    },
    // 过滤任务完成状态
    filterHandler_taksState(value, row, column) {
      return value === '全部完成' ? row.taskStateCount === value : row.taskStateCount !== '全部完成'
    },
    // 过滤批阅状态
    filterHandler_reviewState(value, row, column) {
      return value == '已全部批阅' ? row.reviewStateCount === value : row.reviewStateCount !== '已全部批阅'
    },
    // 格式化任务项的内容
    taskStateFormatter(row, column) {
      const userID = row.userID;
      const findStuData = this.studentsList.find(
        (item) => item.userID === userID
      );
      let count =
        findStuData.studyingTaskIDArray.length +
        findStuData.notStartTaskIDArray.length;
      if (findStuData) {
        if (
          findStuData.studyingTaskIDArray.length ||
          findStuData.notStartTaskIDArray.length
        ) {
          const message = `有${count}个任务未完成`;
          this.$set(row, "taskStateCount", message);
          return message;
        } else {
          this.$set(row, "taskStateCount", "全部完成");
          return "全部完成";
        }
      } else {
        const message = `有${count}个任务未完成`;
        this.$set(row, "taskStateCount", message);
        return message;
      }
    },
    // 格式化批阅项的内容
    reviewStateFormatter(row, column) {
      let context = "";
      const findNoReview = row.finishedTaskResultArray.filter(item => item.reviewState == "在批" || item.reviewState == "未批")
      if (findNoReview.length || !row.finishedTaskResultArray?.length) {
        context = `有${findNoReview.length || row.totalTaskCount}个任务未批阅`;
      } else {
        context = "已全部批阅"
      }

      this.$set(row, "reviewStateCount", context);
      return context;

      // row.allTaskResultsInChooseNo.forEach((taskItem, t) => {
      //   let noReview = taskItem.guidelines.filter(
      //     (guideline) =>
      //       guideline.guidelineComment == "" &&
      //       (guideline.guidelineScore == -8 ||
      //         guideline.gameOrExciseScore == -8)
      //   );
      //   if (noReview.length == taskItem.guidelines.length) {
      //     context = `有${noReview.length}个任务未批阅`;
      //     return;
      //   }
      //   let reviewing = taskItem.guidelines.filter(
      //     (guideline) =>
      //       guideline.guidelineComment !== "" &&
      //       (guideline.guidelineScore !== -8 ||
      //         guideline.gameOrExciseScore !== -8)
      //   );
      //   if (
      //     reviewing.length !== 0 &&
      //     reviewing.length == taskItem.guidelines.length &&
      //     context !== `有${noReview.length}个任务未批阅`
      //   ) {
      //     context = "已全部批阅";
      //   } else {
      //     if (!taskItem.guidelines.length) return;
      //     context = `有${noReview.length}个任务未批阅`;
      //   }
      // });
    },
    // 查看详情
    async handleOpenDetail(row, isTask, that) {
      that = that || this
      const { query } = that.$route
      let color = {
        未学: "#F56161",
        在学: "#F9C957",
        已学: "#91CD74",
        未批阅: "#F56161",
        在批阅: "#F9C957",
        已批阅: "#91CD74",
      };
      let data = [];
      // 判断是否存在学习数据 没有则调用父组件的函数获取该学生的学习数据
      if (!row.allTaskResultsInChooseNo || row.isGetOnlyTask) {
        const findUserData = that.studentsList.find(item => item.userID == row.userID)
        if (findUserData?.allTaskResultsInChooseNo && findUserData?.getAllTask && !findUserData.isGetOnlyTask) row.allTaskResultsInChooseNo = findUserData.allTaskResultsInChooseNo
        else return that.handleGetStuData(row.userID, that.handleOpenDetail, {row, isTask, that})
      }
      if (isTask) {
        const taskSunData = {
          未学: [],
          在学: [],
          已学: [],
        };

        row.allTaskResultsInChooseNo.forEach((taskItem) => {
          const { taskID } = taskItem;
          const taskGroupID = that.taskIDforTaskGruopID[taskID];
          const taskName =
            that.courseInfo.taskGroups[taskGroupID].tasks.find(
              (tItem) => tItem.taskID == taskID
            )?.name || "无任务名";
          taskSunData[taskItem.state].push({ name: taskName, value: 1 });
        });
        data = that.objectToArrayTree(taskSunData, color);
      } else {
        const reviewSunData = {
          未批阅: [],
          在批阅: [],
          已批阅: [],
        };

        row.allTaskResultsInChooseNo.forEach((taskItem) => {
          const { taskID } = taskItem;
          const taskGroupID = that.taskIDforTaskGruopID[taskID];
          const taskName =
            that.courseInfo.taskGroups[taskGroupID].tasks.find(
              (tItem) => tItem.taskID == taskID
            )?.name || "无任务名";
          let noReview = taskItem.guidelines.filter(
            (guideline) =>
              guideline.guidelineComment == "" &&
              (guideline.guidelineScore == -8 ||
                guideline.gameOrExciseScore == -8)
          );
          if (noReview.length == taskItem.guidelines.length) {
            reviewSunData["未批阅"].push({ name: taskName, value: 1 });
            return;
          }
          let reviewing = taskItem.guidelines.filter(
            (guideline) =>
              guideline.guidelineComment !== "" &&
              (guideline.guidelineScore !== -8 ||
                guideline.gameOrExciseScore !== -8)
          );
          if (
            reviewing.length !== 0 &&
            reviewing.length == taskItem.guidelines.length
          ) {
            reviewSunData["在批阅"].push({ name: taskName, value: 1 });
          } else {
            if (!taskItem.guidelines.length) return;
            reviewSunData["已批阅"].push({ name: taskName, value: 1 });
          }
        });
        data = that.objectToArrayTree(reviewSunData, color);
      }
      that.show = true;
      that.isTask = isTask;
      that.currStu = row;
      that.sunChartData = data;
    },
    handleCloseDialog() {
      this.show = false;
      this.sunChartData = [];
    },
    // 将对象转换成二级树形数组
    objectToArrayTree(obj, color) {
      const data = [];
      Object.keys(obj).forEach((item, index) => {
        data[index] = { name: item, children: obj[item] };
        color[item] && (data[index].itemStyle = { color: color[item] });
        if (data[index]?.children && Array.isArray(data[index].children)) {
          data[index].children.forEach((citem) => {
            citem.itemStyle = { color: color[item] };
          });
        }
      });
      return data;
    },
    // 格式化姓名
    formatterName(row) {
      return (
        row.realName || row.nickName || row.email || row.regName || row.stuNum
      );
    },
    handleGetStuData(userID, fn, data) {
      this.$emit("getStuData", userID, fn, data)
    }
  },
};
</script>

<style lang="stylus">
.statisticsInfo-task {
  .statisticsInfo-head {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .pieChartBox {
      height: 252px;
      display: flex;
      flex-flow: column;
      justify-content: space-between;
      align-items: flex-start;

      .pieChart {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 10px;
        background-color: #ffffff;
        width: 398px;
        height: 206px;
      }

      .searchInput {
        .el-input {
          width: 230px;

          .el-input__inner {
            height: 36px;
            background-color: #ffffff;
            border: solid 1px rgba(112, 112, 112, 0.2);
          }
        }
      }
    }

    .barChart {
      width: 750px;

      .carouselEcharts {
        margin: 0;
        box-shadow: none;
        background: #fff;
        border-radius: 10px;
      }

      .echartsBar {
        padding: 0;
      }
    }
  }

  .tableBox {
    margin-top: 10px;
  }
}
</style>